﻿CREATE PROCEDURE [maint].[RestoreLogFromDevice]
@DbName [sysname], @DeviceName [sysname], @FilePosition INT, @Recover BIT, @StopAtTime DATETIME, @OutputDiagnostics BIT=0
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @RC int, @ErrorMessage nvarchar(max);
	SET @RC = 0;

	IF(@OutputDiagnostics = 1)
		BEGIN
			PRINT OBJECT_NAME(@@PROCID)
			PRINT N'	@DbName = N''' + ISNULL(@DbName,N'NULL') + ''''
			PRINT N'	@DeviceName = N''' + ISNULL(@DeviceName,N'NULL') + ''''
			PRINT N'	@FilePosition = N''' + ISNULL(CAST(@FilePosition AS nvarchar),N'NULL') + ''''
			PRINT N'	@Recover = N''' + ISNULL(CAST(@Recover AS nvarchar),N'NULL') + ''''
			PRINT N'	@StopAtTime = N''' + ISNULL(CAST(@StopAtTime AS nvarchar(20)),N'NULL') + ''''
		END

	BEGIN TRY
	
		DECLARE @LogRestoreStatement nvarchar(1024)
		SET @LogRestoreStatement = 
			N'RESTORE LOG [' + @DbName + N'] 
			FROM [' + @DeviceName + N']
			WITH 
			FILE = ' + CAST(@FilePosition AS nvarchar)
			+ (CASE
				WHEN   (@StopAtTime IS NOT NULL) THEN N', STOPAT=''' + CAST(@StopAtTime AS nvarchar(20)) + N''''
				ELSE N''
			END)
			+ (CASE
				WHEN @Recover = 1 THEN N', RECOVERY'
				ELSE N', NORECOVERY'
			END)
			+ N', STATS = 10';

		IF(@OutputDiagnostics = 1)
			PRINT N'	@LogRestoreStatement = ' + CHAR(10) + ISNULL(@LogRestoreStatement,N'NULL') + CHAR(10);

		DECLARE @StartDate datetime
		SET @StartDate = GETDATE();
		
		EXEC(@LogRestoreStatement);
		
	END TRY
	BEGIN CATCH
		SET @RC = ERROR_NUMBER();
		EXEC [util].[GetErrorOutput] @Output = @ErrorMessage OUTPUT;
	END CATCH

	DECLARE @FinishDate datetime;
	SET @FinishDate = GETDATE();
	
	EXEC @RC = [maint].[LogRestore]
		 @DbName = @DbName
		,@DeviceName = @DeviceName
		,@FilePosition = @FilePosition
		,@Type = 5
		,@StartDate = @StartDate
		,@FinishDate = @FinishDate
		,@RestorePoint = @StopAtTime
		,@RecoverStatus = @Recover
		,@ErrorCode = @RC
		,@Output = @ErrorMessage
		,@OutputDiagnostics = @OutputDiagnostics;

	RETURN(@RC);
END;